package com.xigege.nio.零拷贝.nio零拷贝;

import java.io.FileInputStream;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.FileChannel;
import java.nio.channels.SocketChannel;

public class NewIOClient {
    public static void main(String[] args)throws IOException {
        SocketChannel socketChannel = SocketChannel.open();

        socketChannel.connect(new InetSocketAddress("localhost", 7001));

        String filename = "protoc-3.6.1-win32.zip";

        //得到一个文件Channel
        FileChannel fileChannel = new FileInputStream(filename).getChannel();

        //准备发送
        long startTime = System.currentTimeMillis();

        //在linux下一个transferTo 方法就可以完成传输
        //在windows下一个transferTo方法只能发送8mb，就需要分段传输文件，而且要注意传输时的位置
        //transferTo底层使用了0拷贝
        //第一个参数position表示从哪里开始传，第二个参数表示传多少个字节
        long transferCount = fileChannel.transferTo(0, fileChannel.size(), socketChannel);

        System.out.println("发送的总的字节数 = " + transferCount + "耗时：" + (System.currentTimeMillis() - startTime) );

        //关闭
        fileChannel.close();
    }
}
